<?php
class TimelinesController extends AppController{
	public $components = array ('Session');
	public $helper = array ('Html'=>'Form');
	public $userId =1;
	public $uses = array('User','Timeline','Tweet','Place','Favorite','Mention','Follow');


	public function beforeFilter() {
		parent::beforeFilter();
		$mobile = preg_match('/android/i',$_SERVER['HTTP_USER_AGENT']);
		if($mobile){
			$this->autoRender =false;
		}
		else{
			//echo $_SERVER['HTTP_USER_AGENT'];
			$this->autoRender = false;
		}
	}
	public  function index(){


	}

	public function home_timeline(){

		$this->autoRender = true;

		$err = null;
		$response=array();

		if($this->request->is('post')){
			$this->autoRender = false;
			if(empty($this->request->data['user_id'])){
				$err .= "not found user_id param";

			}
			if(!isset($this->request->data['max_tweet_id'])){
				$err .= "not found max_tweet_id param";
					
			}

			if(!isset($this->request->data['count'])){
				$err .= "not found count param";

			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				$user_id = $this->request->data['user_id'];
				$userId = $this->request->data['user_id'];
				$count = $this->request->data['count'];
				$maxTweetId = $this->request->data['max_tweet_id'];
				if($maxTweetId<0){
					$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
					, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime , not isnull(Favorite.id) as favorite ,not isnull(RTByme.id) as retweetedbyme,Retweet.*,ParentUser.*
					from timelines as Timeline
					inner join tweets as Tweet
					on Timeline.user_id = '.$userId.' and
					Timeline.tweet_id = Tweet.id
					inner join users as User
					on User.id = Tweet.user_id
					left join tweets as Retweet
					on Tweet.type = 3 and Tweet.parent_id = Retweet.id
					left join users as ParentUser
					on Tweet.type = 3 and Retweet.user_id = ParentUser.id
					left join favorites as Favorite
					on (Tweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.') or
					(Retweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.')
					left join tweets as RTByme
					on RTByme.type =3 and (
					(RTByme.user_id = '.$userId.'  and RTByme.parent_id =Tweet.id) or
					(RTByme.user_id = '.$userId.'  and RTByme.parent_id =ReTweet.id))
					order by Tweet.id DESC
					Limit '.$count;
				}
				else {
					$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created
					, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,not isnull(RTByme.id) as retweetedbyme,Retweet.*,ParentUser.*
					from timelines as Timeline
					inner join tweets as Tweet
					on Timeline.user_id = '.$userId.' and
					Timeline.tweet_id < ' . $maxTweetId.' and
					Timeline.tweet_id = Tweet.id
					inner join users as User
					on User.id = Tweet.user_id
					left join tweets as Retweet
					on Tweet.type = 3 and Tweet.parent_id = Retweet.id
					left join users as ParentUser
					on Tweet.type = 3 and Retweet.user_id = ParentUser.id
					left join favorites as Favorite
					on (Tweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.') or
					(Retweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.')
					left join tweets as RTByme
					on RTByme.type =3 and (
					(RTByme.user_id = '.$userId.'  and RTByme.parent_id =Tweet.id) or
					(RTByme.user_id = '.$userId.'  and RTByme.parent_id =ReTweet.id))
					order by Tweet.id DESC
					Limit '.$count;
				}
				
				$response =$this->Timeline->getDataSource()->query($query);
				//debug ($response);
				//die;
// 				$this->Timeline->unbindModel(array('belongsTo' =>array('User')));
// 				if($this->request->data['max_tweet_id']<0){
// 					$response = $this->Timeline->find('all',array( 'fields'=>array('Tweet.*','(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime '),
// 							'recursive'=>1,
// 							'conditions'=>
// 							array('Timeline.user_id '=>$user_id),
// 							'limit'=>$count,
// 							'order' => array('Timeline.tweet_id DESC'))
// 					);

// 				}
// 				else{
// 					$response = $this->Timeline->find('all',array('fields'=>array('Tweet.*','(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime '),
// 							'recursive'=>1,
// 							'conditions'=>
// 							array('Timeline.user_id '=>$user_id,
// 									'Timeline.tweet_id < ' =>$maxtweet),
// 							'limit'=>$count,
// 							'order' => array('Timeline.tweet_id DESC'))
// 					);
// 				}
// 				foreach($response as $key => $value){
// 					//debug($key);
// 					//lay thong tin user tweet tweet nay
// 					//debug($value);
// 					$user_id= $value['Tweet']['user_id'];
// 					$ownerTweet = $this->User->find('first',array('recursive'=>-1,
// 							'conditions'=>array('User.id'=>$user_id)));
// 					$response[$key]['User']=$ownerTweet['User'];
// 					//add favorite neu user hien tai thich tweet nay
// 					$tweet_id = $value['Tweet']['id'];
// 					$favoriteUser= $this->request->data['user_id'];
// 					$favorite = $this->Favorite->find('first',array('recursive'=>-1,
// 							'conditions'=>array('tweet_id'=>$tweet_id,'user_id'=>$favoriteUser)));
// 					//debug($favorite);
// 					if($favorite){
// 						$response[$key]['Tweet']['favorite']='1';
// 					}
// 					else{
// 						$response[$key]['Tweet']['favorite']='0';
// 					}

// 					//add noi dung cua tweet cha trong truong hop day la mot retweet
// 					$parentTweet = $value['Tweet']['parent_id'];
// 					$type = $value['Tweet']['type'];
// 					if($type == 3){
// 						$retweet= $this->Tweet->find('first',array('recursive'=>-1,
// 								'conditions'=>array('Tweet.id'=>$parentTweet),
// 								'fields'=>array('Tweet.*','(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime ')));
// 						$ownerReTweetId = $retweet['Tweet']['user_id'];
// 						$ownerOfRetweet = $this->User->find('first',array('recursive'=>-1,
// 								'conditions'=>array('User.id'=>$ownerReTweetId)));

// 						$response[$key]['Tweet']['retweet']['Tweet']=$retweet['Tweet'];
// 						$response[$key]['Tweet']['retweet']['0']=$retweet['0'];
// 						$response[$key]['Tweet']['retweet']['User']= $ownerOfRetweet['User'];
// 						//debug($retweet);
// 					}
// 					else{
// 						$response[$key]['Tweet']['retweet']['Tweet']=array();
// 						$response[$key]['Tweet']['retweet']['0']=array();
// 						$response[$key]['Tweet']['retweet']['User']= array();
// 					}

// 					$retweeted = $this->Tweet->find('first',
// 							array('conditions'=>array('Tweet.type'=>3,'Tweet.user_id'=>$userId,'Tweet.parent_id'=>$value['Tweet']['id']),'recursive'=>-1));

// 					if($retweeted==null){
// 						$response[$key]['Tweet']['retweetedbyme']='0';

// 					}
// 					else{
// 						$response[$key]['Tweet']['retweetedbyme']='1';
// 					}
// 					//debug($response[$key]);
// 					//debug($ownerTweet);
// 				}
					
				//debug($response);
				$response = array("status_code" => 0,"message" => 'Ok',"entity" =>$response);

			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>$response);
			}
			echo json_encode($response);

		}
		//$this->redirect("http://faketwitter.com/tweets");

	}

	public function user_timeline(){

		//$this->autoRender = false;

		$err = null;
		$response=array();

		if($this->request->is('post')){
			if(empty($this->request->data['user_id'])){
				$err .= "not found user_id param";

			}
			if(!isset($this->request->data['max_tweet_id'])){
				$err .= "not found max_tweet_id param";
					
			}

			if(!isset($this->request->data['count'])){
				$err .= "not found count param";

			}
			//debug($this->request->data);
			//debug(empty($err));
			if(empty($err)){
				$userId = $this->request->data['user_id'];
				$count = $this->request->data['count'];
				$maxTweetId = $this->request->data['max_tweet_id'];
				//$this->Timeline->unbindModel(array('belongsTo' =>array('User')));
				
				if($maxTweetId<0){
					$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,(Tweet.type=3) as retweetedbyme,Retweet.*,ParentUser.*
					from tweets as Tweet
					inner join users as User
					on Tweet.user_id = '.$userId.' and
				    User.id = Tweet.user_id
					left join tweets as Retweet
					on Tweet.type = 3 and Tweet.parent_id = Retweet.id
					left join users as ParentUser
					on Tweet.type = 3 and Retweet.user_id = ParentUser.id
					left join favorites as Favorite
					on (Tweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.') or
					(Retweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.')
					order by Tweet.id DESC
					Limit '.$count;
				}
				else {
					$query =  'select User.id ,User.avatar,User.username,User.email,User.screen_name,User.created, Tweet.*,(TIMEDIFF(UTC_TIMESTAMP(),Tweet.created)) as leftTime, not isnull(Favorite.id) as favorite ,(Tweet.type=3) as retweetedbyme,Retweet.*,ParentUser.*
					from tweets as Tweet
					inner join users as User
					on Tweet.user_id = '.$userId.' and
					Tweet.tweet_id < ' . $maxTweetId.' and
				    User.id = Tweet.user_id
					left join tweets as Retweet
					on Tweet.type = 3 and Tweet.parent_id = Retweet.id
					left join users as ParentUser
					on Tweet.type = 3 and Retweet.user_id = ParentUser.id
					left join favorites as Favorite
					on (Tweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.') or
					(Retweet.id = Favorite.tweet_id and Favorite.user_id = '.$userId.')
					order by Tweet.id DESC
					Limit '.$count;
				}
				
				$response =$this->Timeline->getDataSource()->query($query);
				//debug ($response);
				
					
				//debug($response);
				$response = array("status_code" => 0,"message" => 'Ok',"entity" =>$response);

			}
			else {
				$response = array("status_code" => -1,"message" => $err,"entity" =>$response);
			}
			echo json_encode($response);

		}
		//$this->redirect("http://faketwitter.com/tweets");

	}


}